var Q = require('q'),
    entityCollection = require('../../../Base/server/controllers/EntityCollection'),
    departmentController = require('./Department.server.controller');

//查找所有交接区ID
exports.distinctId = function (completeFun) {
    var connectArea = entityCollection.getEntity("WareHouse");
    connectArea.Entity.collection.distinct('_id', function (err, records) {
        if (err) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询错误';
            newErr.message = '查询看板需求错误，请检查查询参数！';
            completeFun(newErr);
        } else {
            completeFun(null, records);
        }
    });
};

exports.getConnectAreaByDepartment = function (queryCondition, completeFun) {
    var entity = entityCollection.getEntity("WareHouse");
    entity.findOne(queryCondition, null, function (err, result) {
        if (err) {
            completeFun(err);
        } else {
            completeFun(null, result);
        }
    });
};

//通过作业获取待转区
exports.getWareHouseInfo = function (queryCondition, completeFun) {
    var entity = entityCollection.getEntity("WareHouse");
    entity.findOne(queryCondition, null, function (err, wareHouseInfo) {
        if (err) {
            completeFun(err);
        } else {
            completeFun(null, wareHouseInfo);
        }
    });
};

// 查找所有转接区
exports.getAll = function () {
    var entity = entityCollection.getEntity("WareHouse");
    return entity.Entity.find({IsEffective: true}, {Code: 1, Name: 1});
};

// 查找所有仓库WareHouse
exports.getAllWareHouse = function (completeFun) {
    var entity = entityCollection.getEntity("WareHouse");
    entity.find({IsEffective: true}, {CreatedOn: -1}, null, function (err, houses) {
        if (err) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询仓库数据错误';
            newErr.message = '请检查查询参数！';
            completeFun(newErr);
        } else {
            completeFun(null, houses);
        }
    });
};

/**
 * 通过部门ID获取仓库信息
 * @param departmentId
 * @param completeFun
 * @author jiadx
 */
exports.getWareHouseInfoByDepartmentId = function (departmentId, completeFun) {
    var entity = entityCollection.getEntity("WareHouse");
    entity.findOne({Department: departmentId}, null, function (err, record) {
        if (err) {
            completeFun(err);
        } else {
            completeFun(null, record);
        }
    });
};

// 根据部门查找仓库
exports.findByDepartment = function (departmentId, projection, populate) {
    var deferred = Q.defer();

    if (!projection) {
        projection = {};
    }
    var entity = entityCollection.getEntity("WareHouse"),
        result = entity.Entity.findOne({ Department: departmentId }, projection);
    if (populate) {
        result = result.populate(populate);
    }

    result.then(function (record) {
        deferred.resolve(record);
    }, function () {
        var newErr = new Error();
        newErr.leval = 9;
        newErr.title = '查询仓库错误';
        newErr.message = '查询失败，请检查查询参数！';
        deferred.reject(newErr);
    });

    return deferred.promise;
};

// 根据部门逐级查找仓库，直到找到为止
exports.findByDepartmentDeep = function (departmentId, projection, populate) {
    var deferred = Q.defer(),
        self = this;

    if (!projection) {
        projection = {};
    }
    var entity = entityCollection.getEntity("WareHouse"),
        result = entity.Entity.findOne({ Department: departmentId }, projection);
    if (populate) {
        result = result.populate(populate);
    }

    result.then(function (record) {
        if (!record) {
            departmentController.findDepartmentById(departmentId, function (err, record) {
                if (err) {
                    deferred.reject(err);
                    return;
                }
                if (!record || !record.ParentDepartment) {
                    var newErr = new Error();
                    newErr.leval = 9;
                    newErr.title = '没有找到仓库';
                    newErr.message = '没有找到仓库！';
                    deferred.reject(newErr);
                    return;
                }
                self.findByDepartmentDeep(record.ParentDepartment, projection, populate).then(function (record) {
                    deferred.resolve(record);
                }, function (err) {
                    deferred.reject(err);
                });
            });
        } else {
            deferred.resolve(record);
        }
    }, function () {
        var newErr = new Error();
        newErr.leval = 9;
        newErr.title = '查询仓库错误';
        newErr.message = '查询失败，请检查查询参数！';
        deferred.reject(newErr);
    });

    return deferred.promise;
};